import { createRouter, createWebHistory } from 'vue-router';
import { useUserStore } from '@/stores/user';
import { staticRoutes, layoutRoute, authRoutes } from './routes';
import http from '@/utils/request';

const router = createRouter({
  history: createWebHistory(),
  routes: [...staticRoutes, layoutRoute],
  scrollBehavior: () => ({ top: 0 })
});

const whiteList = ['/login', '/404', '/front']; // 新增白名单定义

// 启用路由守卫
router.beforeEach(async (to) => {
  const userStore = useUserStore();
  
  // 1. 白名单精确匹配
  if (whiteList.some(path => to.path.startsWith(path))) {
    return true;
  }

  // 2. 权限路由拦截（如/dashboard）
  const isAuthRoute = to.path.startsWith('/dashboard') || to.matched.some(route => route.meta?.requiresAuth);
  
  // 3. 未登录且访问需要权限的路由
  if (!userStore.token && isAuthRoute) {
    return `/login?redirect=${encodeURIComponent(to.fullPath)}`;
  }

  // 4. 已登录处理逻辑保持不变...
  if (userStore.token && !userStore.roles.length) {
    try {
      const infoRes = await http.get('/user/getInfo');
      userStore.roles = infoRes.data.roles;
    } catch (error) {
      userStore.logout();
      return '/login';
    }
  }

  // 动态添加权限路由（只执行一次）
  if (!router.hasRoute('dashboard')) {
    // 添加权限路由
    if (userStore.roles.some(role => ['admin', 'editor'].includes(role))) {
      authRoutes.forEach(route => {
        router.addRoute('layoutRoute', { 
          ...route,
          path: route.path.startsWith('/') ? route.path.slice(1) : route.path // 修正子路由路径格式
        });
      });
    }
  }

  return true;
});

export default router;